package com.zmzncs.lmtc.module.customer.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.zmzncs.lmtc.common.pojo.LoginUser;
import com.zmzncs.lmtc.common.util.ChinaumsUtil;
import com.zmzncs.lmtc.common.util.DateTimeUtil;
import com.zmzncs.lmtc.common.util.ExceptionUtil;
import com.zmzncs.lmtc.common.util.JwtUtil;
import com.zmzncs.lmtc.module.customer.dao.TicketParkMapper;
import com.zmzncs.lmtc.module.customer.pojo.ticket.CustTicketDTO;
import com.zmzncs.lmtc.module.customer.pojo.ticket.CustTicketForm;
import com.zmzncs.lmtc.module.customer.pojo.ticket.CustTicketVO;
import com.zmzncs.lmtc.module.customer.pojo.ticket_park.TicketPark;
import com.zmzncs.lmtc.module.promotion.dao.TicketDao;
import com.zmzncs.lmtc.module.customer.pojo.ticket.CustTicket;
import com.zmzncs.lmtc.module.customer.dao.CustTicketDao;
import com.zmzncs.lmtc.module.promotion.pojo.ticket.Ticket;
import com.zmzncs.lmtc.module.customer.service.CustTicketService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmzncs.lmtc.module.shop.dao.*;
import com.zmzncs.lmtc.module.shop.pojo.park_ticket_set.ParkTicketSet;
import com.zmzncs.lmtc.module.shop.pojo.park_ticket_set_park.ParkTicketSetParkDTO;
import com.zmzncs.lmtc.module.shop.pojo.shop_goods.ShopGoods;
import com.zmzncs.lmtc.module.shop.pojo.shop_park_ticket.ShopParkTicket;
import com.zmzncs.lmtc.module.shop.pojo.shop_ticket.ShopTicket;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.CustomAutowireConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author JD
 * @since 2020-10-09
 */
@Service
public class CustTicketServiceImpl extends ServiceImpl<CustTicketDao, CustTicket> implements CustTicketService {

    @Autowired
    HttpServletRequest request;

    @Autowired
    TicketDao ticketDao;

    @Autowired
    ShopTicketMapper ticketMapper;

    @Autowired
    CustTicketDao custTicketDao;
    @Autowired
    TicketParkMapper ticketParkMapper;
    @Autowired
    ShopGoodsMapper shopGoodsMapper;
    @Autowired
    ShopInfoMapper shopInfoMapper;
    @Autowired
    ParkTicketSetMapper parkTicketSetMapper;
    @Autowired
    ParkTicketSetParkMapper parkTicketSetParkMapper;
    @Autowired
    ShopParkTicketMapper shopParkTicketMapper;


    /**
     * 用户使用优惠券
     */
    @Override
    public CustTicketVO getDiscountAmontWithTicket(CustTicketForm form) {
        LoginUser loginUser = JwtUtil.getLoginUser(request);
        CustTicketVO custTicketVo = new CustTicketVO();
        custTicketVo.setCustTicketId(form.getCustTicketId());

        boolean preferentialMoneyType = false; //满减类型
        boolean discountRateType = false;//折扣类型
        BigDecimal preferentialMoney = BigDecimal.ZERO;
        BigDecimal discountRate = BigDecimal.ZERO;

        CustTicket custTicket = custTicketDao.selectById(form.getCustTicketId());
        if (custTicket == null) {
            ExceptionUtil.businessException("用户:" + loginUser.getCustomerId() + "使用的优惠券不存在");
        }

        //商户端商品购买折扣
        if (form.getRentType().intValue() == 10) {
            if (custTicket.getPreferentialType().intValue() == 1) {
                //  没有超过使用界定金额
                if (custTicket.getUseLimitMoney().compareTo(form.getReceivableAmount()) > 0) {
                    ExceptionUtil.businessException("当前优惠券未到达使用金额标准。");
                }
                preferentialMoneyType = true;
                preferentialMoney = custTicket.getPreferentialMoney();
            } else if (custTicket.getPreferentialType().intValue() == 2) {
                discountRateType = true;
                discountRate = custTicket.getDiscountRate();
            }
        } else {//用户充值购卡折扣
            //  使用类型，1.通用 2.时长 3.月租 4.充值
            // 充值卡类型 0月卡 1时长 2定制月卡 4充值卡
            if (custTicket.getUseType().intValue() == 2 && form.getRentType().intValue() != 1) {
                ExceptionUtil.businessException("优惠券类型不匹配！");
            }

            if (custTicket.getUseType().intValue() == 3 &&
                    (form.getRentType().intValue() != 0 && form.getRentType().intValue() != 2)) {
                ExceptionUtil.businessException("优惠券类型不匹配！");
            }
            if (custTicket.getUseType().intValue() == 4 && form.getRentType().intValue() != 4) {
                ExceptionUtil.businessException("优惠券类型不匹配！");
            }

            //  没有超过使用界定金额
            if (custTicket.getUseLimitMoney().compareTo(form.getReceivableAmount()) > 0) {
                ExceptionUtil.businessException("当前优惠券未到达使用金额标准。");
            }
            if (custTicket.getPreferentialType() != null
                    && custTicket.getPreferentialType().intValue() == 1) { // 满减
                preferentialMoneyType = true;
                preferentialMoney = custTicket.getPreferentialMoney();
            } else if (custTicket.getPreferentialType() != null
                    && custTicket.getPreferentialType().intValue() == 2) { //折扣
                discountRateType = true;
                discountRate = custTicket.getPreferentialMoney();
            }
        }


        if (preferentialMoneyType) {
            custTicketVo.setPaidAmount(form.getReceivableAmount().subtract(preferentialMoney));
        } else if (discountRateType) {
            custTicketVo.setPaidAmount(form.getReceivableAmount().multiply(discountRate.multiply(new BigDecimal("0.1"))));
        }
        custTicketVo.setReceivableAmount(form.getReceivableAmount());
        custTicketVo.setCustomerId(form.getCustomerId());
        custTicketVo.setTicketId(form.getTicketId());

        if (custTicketVo.getPaidAmount().compareTo(BigDecimal.ZERO) <= 0) {
            custTicketVo.setPaidAmount(new BigDecimal("0.01"));
        }
        custTicketVo.setPaidAmount(custTicketVo.getPaidAmount().setScale(2, BigDecimal.ROUND_UP));
        custTicketVo.setDiscountAmount(form.getReceivableAmount().subtract(custTicketVo.getPaidAmount()));
        return custTicketVo;
    }

    /**
     * 查询未使用-且当前可用的券
     **/
    @Override
    public List<CustTicketDTO> getNotExpiredValidTicket(Integer cardType, String amount,Long goodsId) {
        LoginUser loginUser = JwtUtil.getLoginUser(request);
        ShopGoods shopGoods = new ShopGoods();
        if (cardType == 10 && goodsId != null) {
            shopGoods = shopGoodsMapper.selectById(goodsId);
        } else if (cardType == 10 && goodsId == null) {
            ExceptionUtil.businessException("购买商品查询可使用优惠券，商品Id不能为空！");
        }


        //用户选择服务费用
        BigDecimal amountMoney = new BigDecimal(amount);
        List<CustTicketDTO> list = custTicketDao.getNotExpiredValidTicket(loginUser.getCustomerId(), cardType,shopGoods.getShopId());
        for (int i = list.size() - 1; i >= 0; i--) {
            BigDecimal useLimitMoney = list.get(i).getUseLimitMoney();
            //剔除满减限额小于用户购买用户金额的优惠券
            if (amountMoney.compareTo(useLimitMoney) < 0) {
                list.remove(i);
            }
        }
        return list;
    }

    /**
     * 查询未使用-不一定可用
     **/
    @Override
    public List<CustTicketDTO> getNotExpiredTicket() {
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        //  查询未使用
        List<CustTicketDTO> custTicketDTOList = custTicketDao.getNotExpiredTicket(loginUser.getCustomerId());
        for(CustTicketDTO custTicketDTO: custTicketDTOList){
            //  商品优惠券
            if(custTicketDTO.getUseType().equals(10)){
//                custTicketDTO.get
//                shopInfoMapper
            }
        }

        return custTicketDao.getNotExpiredTicket(loginUser.getCustomerId());
    }

    /**
     * -查询-已使用
     **/
    @Override
    public List<CustTicketDTO> getUsedTicket() {
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        return custTicketDao.getUsedTicket(loginUser.getCustomerId());
    }

    /**
     * 查询-已过期
     **/
    @Override
    public List<CustTicketDTO> getExpireTicket() {
        LoginUser loginUser = JwtUtil.getLoginUser(request);
        return custTicketDao.getExpireTicket(loginUser.getCustomerId());
    }

    /**
     * 查询-需要首页提醒的优惠券
     *
     * @param customerId
     **/
    @Override
    public List<CustTicketDTO> getTipsTicket(Long customerId) {
        //  更新客户端优惠券提示信息
        custTicketDao.updateTipsStatus(customerId);

        return custTicketDao.getTipsTicket(customerId);
    }

    /**
     * 领取优惠券
     */
    @Override
    @Transactional
    public void receiveTicket(Long ticketId) {
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        //  查询优惠券
        ShopTicket ticket = ticketMapper.selectById(ticketId);
        if (ticket.getStock() <= 0) {
            ExceptionUtil.businessException("已领完");
        }
        if (ticket.getIsLimitQuantity().equals(1)) {
            List<CustTicketDTO> reservedTicketList = custTicketDao.getReservedTicket(loginUser.getCustomerId(), ticketId);
            if (reservedTicketList.size() >= ticket.getLimitQuantity()) {
                ExceptionUtil.businessException("每人最多可领取" + ticket.getLimitQuantity() + "个");
            }
        }

        //  添加客户优惠券
        CustTicket custTicket = new CustTicket();
        BeanUtils.copyProperties(ticket, custTicket);
        custTicket.setId(null);
        custTicket.setStatus(0);
        custTicket.setTicketId(ticketId);   //  优惠券id
        custTicket.setShopId(ticket.getShopId());
        custTicket.setUseLimitMoney(ticket.getMinimumMoney());
        custTicket.setPreferentialMoney(ticket.getOffsetMoney());
        custTicket.setDiscountRate(ticket.getDiscountRate());
        custTicket.setGrantType(3); //  发放类型，1：平台发放，2：活动发放，3：领取
        custTicket.setUseType(10); //  使用类型，1：停车场通用，2：时长，3：月租，4：充值，10：商品
        custTicket.setUseBeginTime(new Date());  //  使用开始时间
        custTicket.setUseEndTime(DateTimeUtil.getDayEnd(DateTimeUtil.getNextDayDate(new Date(), ticket.getExpiryDays())));   //  使用结束时间
        custTicket.setReceiveTime(new Date());   //  领取时间
        custTicket.setCustomerId(loginUser.getCustomerId());   //  客户id
        custTicketDao.insert(custTicket);

        //  减库存
        ticket.setStock(ticket.getStock() - 1);
        ticketMapper.updateById(ticket);
    }

    @Override
    @Transactional
    public void receiveParkTicket(Long parkTicketSetId) {
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        //  查询商户停车券
        ParkTicketSet parkTicketSet = parkTicketSetMapper.selectById(parkTicketSetId);
        if (parkTicketSet == null) {
            ExceptionUtil.businessException("领取的停车券不存在");
        }
        if (parkTicketSet.getQuantity() <= 0) {
            ExceptionUtil.businessException("已领完");
        }
        if (parkTicketSet.getLimitQuantityPerson().equals(1)) {
            List<CustTicketDTO> reservedTicketList = custTicketDao.getReservedTicket(loginUser.getCustomerId(), parkTicketSetId);
            if (reservedTicketList.size() >= parkTicketSet.getLimitQuantityPerson()) {
                ExceptionUtil.businessException("每人最多可领取" + parkTicketSet.getLimitQuantityPerson() + "个");
            }
        }

        ShopParkTicket shopParkTicket = shopParkTicketMapper.selectById(parkTicketSet.getShopParkTicketId());

        //  添加客户优惠券
        CustTicket custTicket = new CustTicket();
        custTicket.setTicketId(parkTicketSetId);
        custTicket.setTicketName(shopParkTicket.getParkingDuration() + "小时停车券");
        custTicket.setTicketCode(ChinaumsUtil.getWriteOffCode());
        custTicket.setCustomerId(loginUser.getCustomerId());   //  客户id
        custTicket.setUseLimitMoney(new BigDecimal(0));
        custTicket.setTipsStatus(1);
        custTicket.setPreferentialType(3);
        custTicket.setParkingDuration(shopParkTicket.getParkingDuration());
        custTicket.setUseType(11);
        custTicket.setShopId(shopParkTicket.getShopId());
        custTicket.setStatus(2);
        custTicket.setGrantType(3); //  发放类型，1：平台发放，2：活动发放，3：领取
        custTicket.setExpiryDays(0);
        custTicket.setValidityDays(shopParkTicket.getToBeUsedValidityDays());
        custTicket.setToBeActivatedValidityDays(parkTicketSet.getToBeActivatedValidityDays());
        custTicket.setReceiveTime(new Date());   //  领取时间
        Date nextDayDate = DateTimeUtil.getNextDayDate(new Date(), parkTicketSet.getToBeActivatedValidityDays());
        custTicket.setToBeActivatedExpiryTime(DateTimeUtil.getDayEnd(nextDayDate));
        custTicketDao.insert(custTicket);

        List<ParkTicketSetParkDTO> parkList = parkTicketSetParkMapper.getBySetId(parkTicketSetId);
        if (parkList == null || parkList.size() <= 0) {
            ExceptionUtil.businessException("领取的停车券没有配置停车场");
        }
        for (ParkTicketSetParkDTO setParkDTO : parkList) {
            TicketPark ticketPark = new TicketPark();
            ticketPark.setCustTicketId(custTicket.getId());
            ticketPark.setParkId(setParkDTO.getParkId());
            ticketParkMapper.insert(ticketPark);
        }

        //  减库存
        parkTicketSet.setQuantity(parkTicketSet.getQuantity() - 1);
        parkTicketSetMapper.updateById(parkTicketSet);
    }

}
